package com.heima.behavior.Service.Impl;

import com.heima.behavior.Service.BehaviorService;
import com.heima.model.common.Behavior.KafkaStream;
import com.heima.model.common.Behavior.dto.BehaviorDto;
import com.heima.model.common.Behavior.dto.LikeBehaviorDto;
import com.heima.model.common.Behavior.dto.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class BehaviorServiceImpl implements BehaviorService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 点赞/取消
     */
    @Override
    public ResponseResult likerBehavior(LikeBehaviorDto dto) {
        Long userId = UserContext.getUserId();
        if (userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String key = "like:" + dto.getArticleId();
        redisTemplate.opsForHash().put(key,userId,dto.getOperation());
        String k = key+":"+dto.getOperation();
        kafkaTemplate.send(KafkaStream.ARTIC_SOURCE,k,"1");
        log.info(k);
        return ResponseResult.okResult();
    }

    /**
     * 阅读
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        Long userId = UserContext.getUserId();
        String key = "read:"+dto.getArticleId();
        if (userId==null){
            redisTemplate.opsForHash().increment(key,0,1);
        }
        redisTemplate.opsForHash().increment(key,userId,1);
        kafkaTemplate.send(KafkaStream.ARTIC_SOURCE,key,"2");
        log.info(key);
        return ResponseResult.okResult();
    }


    /**
     *  文章收藏
     */
    @Override
    public ResponseResult collectionBehavior(BehaviorDto dto) {
        return null;
    }
}
